/**
 * For the license, see main.cpp file
 */

#include "SettingsExpert.h"
#include "Qrm3Controller.h"
#include "SettingsGlobalResource.h"

SettingsExpert::SettingsExpert()
{

	/**
	 * NOTE:
	 *
	 * Unix | Mac OS X:
	 * -> $HOME/.config/com.QRm3WiFi/qrm3wifi.ini
	 *
	 * On Windows:
	 * -> %APPDATA%\com.QRm3WiFi\qrm3wifi.ini
	 *
	 * The %APPDATA% path is usually C:\Documents and Settings\UserName\Application Data;
	 */
	
	settings = new QSettings(QSettings::IniFormat, QSettings::UserScope, "com.QRm3WiFi", "qrm3wifi");
	
	if(! settings->contains(SETTING_FIRST_TIME) )
	{
		restoreDefaultSettings(false);	//don't update the gui now. It cause a chain reaction calls!
		
		//set as created
		registerBoolSetting(SETTING_FIRST_TIME, false);
		
		forceSync();
	}
}

/* store the setting with key 'key' and value as QString */
void SettingsExpert::registerQStringSetting(QString key, QString value)
{
	settings->setValue(key, value);
}

/* store the setting with key 'key' and value as QByteArray */
void SettingsExpert::registerQByteArraySetting(QString key, QByteArray value, bool base64)
{
	if(base64)
		settings->setValue(key, value.toBase64());
	else
		settings->setValue(key, value);
}

/* store the setting with key 'key' and value as Unsigned integer (32bit) */
void SettingsExpert::registerQuint32Setting(QString key, quint32 value)
{
	settings->setValue(key, value);
}

/* store the setting with key 'key' and value as Boolean */
void SettingsExpert::registerBoolSetting(QString key, bool value)
{
	settings->setValue(key, value);
}

/* Get the value as *QVariant giving the key */
QVariant SettingsExpert::getSetting(QString key)
{
	return settings->value(key);
}

/* Froce the disk sync (all the changes are phisically stored to disk) */
void SettingsExpert::forceSync()
{
	settings->sync();
}

/**
 * Restore de defaults values (for the authenticator) and update the gui if needed
 */
void SettingsExpert::restoreDefaultSettings(bool updateGui)
{
	/* this is the firs time. fill it. */
	settings->setValue(SETTING_USERNAME, QString(""));
	settings->setValue(SETTING_PASSWORD, QByteArray(""));
	settings->setValue(SETTING_SERVER_IP, QString("193.204.167.81"));
	settings->setValue(SETTING_SERVER_PORT, 1234);
	settings->setValue(SETTING_CRON_TIME, 5);
	settings->setValue(SETTING_SYSTRAY, QSystemTrayIcon::isSystemTrayAvailable());
	
	// Default nick is like 'New#84329'
	qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
	QString nick("New#");
	nick.append(QByteArray::number((unsigned)(qrand() / 10000)));
	
	settings->setValue(SETTINGS_CHAT_NICKNAME, nick);
	settings->setValue(SETTINGS_CHAT_REALNAME, QString(""));

	/* Store now */
	forceSync();

	/* update gui? */
	if(updateGui)
		Qrm3Controller::getInstance()->loadSettingsOnGui();
}
